package milu.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.io.IOUtils;
import org.apache.commons.fileupload.FileUploadException;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.users.*;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import milu.models.*;
import milu.*;

public class EditUser extends HttpServlet {
    public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

        MyUser myUser = (MyUser)request.getAttribute("myUser");
        if(myUser == null) {
            response.sendRedirect("");
        } else {
            request.getRequestDispatcher("/edit-user.jsp").forward(request, response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        MyUser myUser = (MyUser)request.getAttribute("myUser");
		if(myUser == null) {
			LOG.info("user not logged in");
			return;
		}

        // do upload - also handles POST parameters
		// Get the image representation
        String name = "";
        Blob imageBin = null;
        String imageName = "";
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(request);
			while(iter.hasNext()) {
				FileItemStream item = iter.next();
				InputStream stream = item.openStream();

				if(item.isFormField()) {
					String fieldName = item.getFieldName();
					String fieldValue = new String(IOUtils.toByteArray(stream), "utf-8");
					LOG.info("Got a form field: " +fieldName+" with value: "+fieldValue);
					if(fieldName.equals("name")) name = fieldValue;
				} else {
					LOG.info("Got an uploaded file: " +item.getFieldName() +", name = "+item.getName());
					// assign values of image
					imageBin = new Blob(IOUtils.toByteArray(stream));
                    imageName = item.getName();
				}

			}
		} catch (FileUploadException e){
		}

    
        // the myUser session attribute was already created using getObjectById
        // and it was detached, so we can use it to modify or add stuff
        PersistenceManager pm = Datastore.getPersistenceManager();
        try {
            if(!imageName.equals("")) { // we have an uploaded file
                ImageResizer ir = new ImageResizer(imageBin);
                Blob thumbBin = ir.resize("128", "128");
                MyImage avatar = new MyImage(imageName, thumbBin);
                pm.makePersistent(avatar); // save image

                myUser.setAvatarKey(avatar.getKey());
            }

            myUser.setName(name);

            pm.makePersistent(myUser); // save user
        } finally {
            Datastore.finishRequest();
        }

        response.sendRedirect("/edit");
    }
}
